import React from 'react';
import {Form, Row, Col, Button, DatePicker, message ,Divider,Select,Input} from 'antd';
import StatisticsBox from '../../components/box/statistics';
import {sessionManager} from '../../utils/sessionStorage';
import AdjustHis from './AdjustHis';
import {injectIntl} from 'react-intl';
import Grid from '../../components/table/grid';
import axios from 'axios';
import moment from 'moment';
import { getYear } from '../../utils/Array';
import qs from 'qs';
const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
class merchantStatistics extends React.Component {
	constructor(props) {
		super(props);
		this.common = this.props.intl.messages.common;
		this.columns = [
			{
				title: '用户账号',
				width: '150',
				dataIndex:'account',
				key: 'account'
			},
			{
				title: '公司名称',
				dataIndex: 'company_name',
				key: 'company_name',
				width: '150',
			},
			{
				title: '公司地址',
				dataIndex: 'company_address',
				key: 'company_address',
				width: '150',
			},
			{
				title: '公司电话',
				dataIndex: 'company_phone',
				key: 'company_phone',
				width: '150',
			},
			{
				title: '负责人姓名',
				dataIndex: 'chief_name',
				key: 'chief_name',
				width: '150',
			},
			{
				title: '账单金额（元）',
				dataIndex: 'fee_total',
				key: 'fee_total',
				width: '150',
			},
			{
				title: this.common.operation,
				key: 'action',
				fixed: 'right',
				width: 200,
				render: (text, record) => (
					<div>
						<span>
								<a onClick={() => this.goLink(text, record, 'ledgerMonthStatDetail')}>结算明细</a>
								<Divider type="vertical"/>
						</span>
						<span>
								<a onClick={() => this.goLink(text, record, 'childSettlelist')}>下级结算列表</a>
						</span>
					</div>
				)
			}
		];
		this.state = {
			params:{
				// timeBegin: moment(new Date()).format('YYYY.MM.DD'),
				// timeEnd: moment(new Date()).format('YYYY.MM.DD'),
			},
			summary: [],
			visible: false,
			refresh:0
		}
	}

	componentWillMount() {
		this.getBillTotal()
	}

	getBillTotal(start, end){
		const NowDateStart= start || moment(new Date()).format('YYYY.MM.DD');
		const NowDateEnd= end || moment(new Date()).format('YYYY.MM.DD');

		axios.get('/api/settlement/billSplit/splitRecord',{params:{
				timeBegin:NowDateStart,
				timeEnd:NowDateEnd
			}}).then(res=>{
			if(res&&res.data){
				const billData=res.data;
				this.setState({
					summary: [
						{
							num: billData.settlementPower||'',
							actions:() =>{
								return (
									<div className="textLeft leftBill">
										<div><span className="label">结算电费</span> <span>{billData.total_power_fee}</span> 元</div>
										<div><span className="label">结算服务费</span> <span>{billData.total_service_fee}</span> 元</div>
										<div><span className="label">结算电量</span> <span>{billData.total_power}</span> 度</div>
									</div>
								)
							}
							// style:{width:400}
						},
						{
							num: billData.total_fee||'',
							unit:'元',
							desc: '结算总费用',
							btn:()=>{
								return(
									<a onClick={() => this.goLink(null, null, 'ledgerMonthStatDetail')} className="a-leftBtn">查看明细</a>
								)
							}
						},
						{
							num: billData.settlementService||'',
							actions:() =>{
								return (
									<div className="textLeft leftBill">
										<div><span className="label">实际电量</span> <span>{billData.selfTotalPower}</span> 度</div>
										<div><span className="label">实际电费</span> <span>{billData.selfTotalPowerFee}</span> 元</div>
										<div><span className="label">实际服务费</span> <span>{billData.selftTotalServiceFee}</span> 元</div>
									</div>
								)
							}
						},
						{
							num: billData.selfTotalFee||'',
							unit:'元',
							desc: '实际总费用'
						}
					],
					NowDateStart:NowDateStart,
					NowDateEnd:NowDateEnd,
					params:{
						timeBegin:NowDateStart,
						timeEnd:NowDateEnd,
						code:billData.CODE, //上级投资人code
					}
				},()=>{
					let GRIDHTML=<Grid url="api/settlement/billSplit/settlementChild" columns={this.columns} refresh={this.state.refresh}  params={this.state.params}/>
					this.setState({
						GRIDHTML:GRIDHTML
					})
				});
			}
		})
	}
	handleCancel = () => {
		this.setState({
			visible: false,
		})
	};

  formSubmit=(data)=>{
    this.setState({
      params: Object.assign(this.state.params, {...data}),
      refresh: this.state.refresh + 1
    }, () => {
      let GRIDHTML=<Grid url="api/settlement/billSplit/settlementChild" columns={this.columns} refresh={this.state.refresh}  params={this.state.params}/>
      this.setState({
        GRIDHTML:GRIDHTML
      });
		});
  }

	goLink = (text, record, link) => {
    this.props.history.push({pathname: `/finance/${link}`, state: {record: text, params: this.state.params}});
	};

	transFormNull=(data)=>{
		for(let i=0;i<data.length;i++){
			if(!data[i].id){
				data[i].id=i
			}
		}
		return data
	}

	transformData=(data)=>{
		return data;
	};

	endTimeLess = (rule, value, callback) => {

		if (value.isAfter(moment().format('YYYY.MM.DD'))) {
			callback(`请选择${moment().format('MM月DD日')}之前的时间`);
		} else {
			callback();
		}
	}

	handleSubmit = (e) => {
		e.preventDefault();
		this.props.form.validateFieldsAndScroll((err, values) => {
			if (!!err) {
				return;
			}
			this.setState({
        refresh: this.state.refresh + 1
      });
			this.getBillTotal(values.rangeTime[0].format('YYYY-MM-DD'), values.rangeTime[1].format('YYYY-MM-DD'));
			// values.startEndTime[0]._i//开始时间
			// values.startEndTime[1]._i//结束时间
			// this.setState(Object.assign(this.state.params,values));
			// this.setState({
			// 	refresh:this.state.refresh+1
			// })
		});
	};

  handleSubmitList = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!!err) {
        return;
      }
      if (values.rangeTime && values.rangeTime.length) {
        values['timeBegin'] = values.rangeTime[0].format('YYYY-MM-DD');
        values['timeEnd'] = values.rangeTime[1].format('YYYY-MM-DD');
        delete values['rangeTime'];
      }
      this.formSubmit(values);
    });
	}

	render() {
		const token=(JSON.parse(sessionStorage.getItem("token"))||{}).token;
		let locale=sessionManager.get('locale');
		let exportQs=`${qs.stringify(this.state.params)}&token=${token}&locale=${locale}`;
		const {getFieldDecorator} = this.props.form;
		const dateFormat = 'YYYY-MM-DD';
		return (
			<div>
				<form >
					<Row gutter={24} type="flex">
						<Col xl={6} xxl={4}>
							<FormItem>
								{getFieldDecorator('rangeTime',
									{
										initialValue:[moment(moment().format(dateFormat)), moment(moment().format(dateFormat))],
										rules: [{
											required:true,
											message: '请选择时间周期'
										}]
									}
								)(
									<RangePicker format={dateFormat} />
								)}
							</FormItem>
						</Col>
						<Col>
							<FormItem>
								<Button type="primary" htmlType="submit"
										onClick={this.handleSubmit} className="ant-btn-84">{this.common.search}</Button>
							</FormItem>
						</Col>
					</Row>
				</form>
				<StatisticsBox params={this.state.summary} />
				<div className={"split-row"}>下级结算列表</div>
				<div>
					<Form>
						<Row gutter={14} type="flex" className={'SC-form'}>
							<Col xl={6} xxl={4}>
								<FormItem label={"所属组"}>
									{getFieldDecorator('roleGroup',{
										initialValue:''
									})(
										<Select placeholder={'处理方式'} allowClear={true}>
											<Option value="">全部</Option>
											<Option value="1">商户</Option>
											<Option value="2">代理</Option>
									
										</Select>
									)}
								</FormItem>
							</Col>
							<Col xl={6} xxl={4}>
								<FormItem label={"用户关键字"}>
									{getFieldDecorator('userKeywords',)(
										<Input placeholder={'账户，名称，公司地址'}/>
									)}
								</FormItem>
							</Col>
							<Col xl={6} xxl={4}>
								<FormItem label={"负责人"}>
									{getFieldDecorator('chiefName',)(
										<Input placeholder={'负责人'} />
									)}
								</FormItem>
							</Col>
							<Col xl={6} xxl={4}>
								<FormItem>
									<Button type="primary" htmlType="submit"
											onClick={this.handleSubmitList} className="ant-btn-84">{this.common.search}</Button>
									<a href={`${axios.defaults.baseURL}/api/billSplit/settlementChild/export?${exportQs}`}>
										<Button type="primary">{this.common.exportStatement}</Button>
									</a>
								</FormItem>
							</Col>
						</Row>
					</Form>
				</div>
				{this.state.GRIDHTML}
				{/*<AdjustHis visible={this.state.visible} handleCancel={this.handleCancel}/>*/}
			</div>
		)
	}
}

merchantStatistics = createForm()(merchantStatistics);
export default injectIntl(merchantStatistics)
